//https://leetcode.cn/problems/valid-parentheses/

#define N 4

typedef int STDatatype;

typedef struct Stakc
{
	STDatatype* a;
	int top;
	int capacity;

}ST;

void STInit(ST* ps)
{
	assert(ps);

	ps->a = (STDatatype*)malloc(sizeof(STDatatype) * N);
	if (ps->a == NULL)
	{
		perror("malloc fail\n");
		return;
	}

	ps->capacity = N;
	ps->top = 0;  //表示栈顶的下一个元素

}

void STDestroy(ST* ps)
{
	assert(ps);

	free(ps->a);
	ps->a = NULL;
	ps->capacity = 0;
	ps->top = 0;
}

void STPush(ST* ps, STDatatype x)
{
	assert(ps);

	if (ps->top == ps->capacity)
	{
		STDatatype* temp = (STDatatype*)realloc(ps->a, sizeof(STDatatype) * (ps->capacity) * 2);
		if (temp == NULL)
		{
			perror("realloc fail\n");
		}

		ps->a = temp;
		ps->capacity *= 2;
	}
	ps->a[ps->top] = x;
	ps->top++;
}

bool STEmpty(ST* ps)
{
	return ps->top == 0;
}

void STPop(ST* ps)
{
	assert(ps);
	assert(!STEmpty(ps));

	ps->top--;

}

int STSize(ST* ps)
{
	assert(ps);

	return ps->top;
}

STDatatype STTop(ST* ps)
{
	assert(ps);
	assert(!STEmpty(ps));

	return ps->a[ps->top - 1];
}

bool isValid(char* s) {
	ST st;
	STInit(&st);
	while (*s)
	{
		//左括号入栈
		if ((*s == '(') || (*s == '[') || (*s == '{'))
		{
			STPush(&st, *s);
		}
		else
		{
			if (STEmpty(&st))
			{
				return false;
				STDestroy(&st);
			}

			//右括号，出栈左括号匹配
			char top = STTop(&st);
			STPop(&st);
			if ((*s == ')' && top != '(') || (*s == ']' && top != '[') || (*s == '}' && top != '{'))
			{
				return false;
				STDestroy(&st);
			}
		}
		s++;
	}
	//bool ret=STEmpty(&st);
	//return ret;
	if (STEmpty(&st))
		return true;
	else
		return false;

}